<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Analytics IFrame</title>
</head>

<body>
    <div>Analytics IFrame</div>
</body>

<script>
    window.onload = () => {
        window.parent.postMessage('Analytics iframe loaded', '*');
    };

    let installationId = '';
    let googleAnalyticsV4Key = '';

    window.onmessage = (event) => {
        if (event.source !== window.parent) { return; }

        // Deserialize event.data, which was received as a JSON string
        const jsonData = JSON.parse(event.data);

        if (!jsonData) {
            return;
        }

        const message = jsonData.message;

        if (message === 'Setup gtag script') {
            // read sent data
            googleAnalyticsV4Key = jsonData.data.googleAnalyticsV4Key;
            installationId = jsonData.data.installationId;


            window.dataLayer = window.dataLayer || [];
            gtag = function () {
                window.dataLayer.push(arguments);
            };

            gtag('js', new Date());
            gtag('config', googleAnalyticsV4Key,
                {
                    client_id: installationId,
                    send_page_view: false,
                    cookie_prefix: 'GA4',
                    cookie_flags: 'SameSite=None;Secure'
                });

            const gtagScript = document.createElement('script');
            gtagScript.type = 'text/javascript';
            gtagScript.setAttribute('src', `https://www.googletagmanager.com/gtag/js?id=${googleAnalyticsV4Key}`);
            document.documentElement.firstChild.appendChild(gtagScript);

            gtagScript.onload = function () {
                window.parent.postMessage('gtag script loaded', '*');
            }
        }

        if (message === 'Set user info') {
            gtag('set',
                {
                    user_id: jsonData.data.userEmail
                });
        }

        if (message === 'Send analytics') {
            gtag('event', jsonData.eventName, { ...jsonData.data });
        }

        if (message === 'Delete GA4 cookies') {
            document.cookie = 'GA4_ga=; SameSite=None; Secure; domain=localhost; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC';
            document.cookie = `GA4_ga_${googleAnalyticsV4Key}=; SameSite=None; Secure; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC`;

            // Cookies deleted. Start iframe reload.
            document.location.reload(true);
        }
    };
</script>

</html>
